import NormalLevelBase from "../../Game/Base/LevelBase";
import level_relationalGraphRoleBase from "./level_relationalGraphRoleBase";
import level_relationalGraphItemBase from "./level_relationalGraphItemBase";

const {ccclass, property} = cc._decorator;

@ccclass
export default class level_relationGraphBase extends NormalLevelBase {
    
    @property({type:cc.ScrollView,tooltip:"所有角色的scrollView"})
    itemScrollView:cc.ScrollView = null;

    @property({type:cc.Prefab,tooltip:"角色item"})
    item:cc.Prefab = null;

    @property({type:cc.Node,tooltip:"移动背景节点"})
    bgNode:cc.Node = null;
    
    @property({type:cc.Node,tooltip:"角色itemContent"})
    roleContent:cc.Node = null;

    @property({type:cc.Node,tooltip:"vaildNodeContent"})
    vaildNodeContent:cc.Node = null;

    @property({type:cc.Label,tooltip:"步数文本"})
    lbStepCount:cc.Label = null;

    @property()
    stepCount:number = 20;

    start(): void {
        this.loadGame();
        this.bgAddEvent();
        this.refrenshStep();
    }

    async loadGame(){
        let allCount:number = this.roleContent.childrenCount;
        let curCount:number = this.vaildNodeContent.childrenCount;
        let needCount:number = allCount - curCount;
        let creatorItem = (item:cc.Node,index:number)=>{
            let nNode:cc.Node = this.roleContent.children[index];
            let ns = nNode.getComponent(level_relationalGraphRoleBase);
            let is:level_relationalGraphItemBase = item.getComponent(level_relationalGraphItemBase);
            is.bindData(ns.getRoleId(),ns.getRoleName());
        }
        for(let i = 0;i<curCount;i++){
            creatorItem(this.vaildNodeContent.children[i],i);
        }
        for(let i:number = 0;i<needCount;i++){
            await new Promise<void>(resolve=>{
                let item:cc.Node = cc.instantiate(this.item);
                let is:level_relationalGraphItemBase = item.getComponent(level_relationalGraphItemBase);
                creatorItem(item,i + curCount);
                item.setParent(this.itemScrollView.content);
                this.oneItemAddEvent(is.headNode);
                this.scheduleOnce(resolve);
            });
        }
    }

    /**
     * 节点增加点击事件
     * @param item 节点
     */
    oneItemAddEvent(item:cc.Node){
        item.on("touchmove",this.onTouchMoveItem,this);
        item.on("touchend",this.onTouchEndItem,this);
        item.on("touchcancel",this.onTouchEndItem,this);
    }

    /**
     * 节点移除事件
     * @param item 节点
     */
    oneItemRemoveEvent(item:cc.Node){
        item.targetOff(this);
    }

    bgAddEvent(){
        this.bgNode.on('touchmove',this.onTouchMoveBg,this);
    }

    onTouchMoveBg(e:cc.Event.EventTouch){
        e.stopPropagation();
        let touches = e.getTouches();
        if (touches.length == 1) {
            let maxXDistance: number = ((this.bgNode.width * this.bgNode.scale) - this.bgNode.parent.width) / 2;
            let maxYDistance: number = ((this.bgNode.height * this.bgNode.scale) - this.bgNode.parent.height) / 2;
            let delta = e.getDelta();
            let dx = delta.x;
            let dy = delta.y;
            if (this.bgNode.x + dx < -maxXDistance) {
                dx = 0;
            }
            if (this.bgNode.x + dx > maxXDistance) {
                dx = 0;
            }
            if (this.bgNode.y + dy < -maxYDistance) {
                dy = 0;
            }
            if (this.bgNode.y + dy > maxYDistance) {
                dy = 0;
            }
            this.bgNode.x += dx;
            this.bgNode.y += dy;
        }
    }

    /**
     * 移动item
     * @param e touch 事件
     */
    onTouchMoveItem(e:cc.Event.EventTouch){
        let targetNode:cc.Node = e.target;
        let detal:cc.Vec2 = e.getDelta();
        targetNode.x += detal.x;
        targetNode.y += detal.y;
    }

    /**
     * 移动item结束
     * @param e touch 事件
     */
    onTouchEndItem(e:cc.Event.EventTouch){
        let targetNode:cc.Node = e.target;
        let parnetNode:cc.Node = targetNode.parent;
        let ps = parnetNode.getComponent(level_relationalGraphItemBase);

        let vaildNode:cc.Node = null;
        this.roleContent.children.forEach((n:cc.Node)=>{
            if(n.getBoundingBoxToWorld().intersects(targetNode.getBoundingBoxToWorld())){
                vaildNode = n;
            }
        });
        //有合法节点
        if(vaildNode){
            let vs = vaildNode.getComponent(level_relationalGraphRoleBase);
            let vid = vs.getRoleId();
            this.subStep();
            if(vid == ps.getRoleId()){
                ps.headChangeBack();
                // 正确 进行矫正位置
                let pos:cc.Vec2 = this. vaildNodeContent.convertToNodeSpaceAR(vaildNode.convertToWorldSpaceAR(cc.v2()));
                parnetNode.setParent(this.vaildNodeContent);
                parnetNode.setPosition(pos);
                parnetNode.removeComponent(cc.Button);
                // 正确一个
                if(this.vaildNodeContent.childrenCount == this.roleContent.childrenCount){
                    // 胜利
                    this.Win(2);
                    return;
                }
            }else{
                // 返回之前的位置
                ps.headChangeBack();
            }
            this.checkStep();
        }else{
            // 返回之前的位置
            ps.headChangeBack();
        }
    }

    subStep(){
        this.stepCount --;
        this.refrenshStep();
    }

    checkStep(){
        if(this.stepCount <= 0){
            // 没有步数了 提示需要增加步数 
            
        }
    }

    refrenshStep(){
        this.lbStepCount.string = this.stepCount.toString();
    }

}
